/** 教程链接：
 * https://dart.cn/language/#exceptions
 */
// Dart 异常处理示例：throw、try-catch-finally、async 异常捕获

import 'dart:io';

// 自定义函数，如果宇航员为 0 则抛出异常
void checkCrew(int astronauts) {
  if (astronauts == 0) {
    throw StateError('No astronauts.');
  }
  print('Crew check passed: $astronauts astronauts on board.');
}

// 异步函数：尝试读取多个文件的内容
Future<void> describeFlybyObjects(List<String> flybyObjects) async {
  try {
    for (final object in flybyObjects) {
      final content = await File('$object.txt').readAsString();
      print('[$object]: $content');
    }
  } on IOException catch (e) {
    print('Could not describe object: $e');
  } finally {
    // 不管有没有错误，都会执行这里
    print('Cleaning up flyby object list...');
    flybyObjects.clear();
  }
}

Future<void> main() async {
  // 示例 1：抛出并捕获同步异常
  try {
    checkCrew(0); // 会抛出异常
  } catch (e) {
    print('Exception caught: $e');
  }

  // 示例 2：处理异步异常
  final objects = ['Mars', 'FakePlanet'];
  await describeFlybyObjects(objects);

  print('Flyby object list is now: $objects'); // 会是空的 []
}
